package com.java.tutorials.spring.BeanPostProcessor;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.ClassPathResource;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

/**
 * Created by xuzhike on 2016/2/1.
 * http://www.java2s.com/Code/Java/Spring/AddBeanPostProcessorToXmlBeanFactory.htm
 * Add BeanPostProcessor To XmlBeanFactory
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath*:Spring-database.xml"})
public class BeanPostProcessorTest {
    @Autowired
    public ApplicationContext ctx;

    @Test
    public void test(){
//        XmlBeanFactory factory = new XmlBeanFactory(new ClassPathResource("context.xml"));
        DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
        XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
        reader.loadBeanDefinitions(new ClassPathResource("Spring-database.xml"));
        BeanInitializationLogger logger = new BeanInitializationLogger();
        factory.addBeanPostProcessor(logger);


        factory.preInstantiateSingletons();
    }

    @Test
    public void test2(){
        ApplicationContext ctx = new ClassPathXmlApplicationContext("Spring-database.xml");
        ctx.getBean("dataSource");
    }
}

class BeanInitializationLogger implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object bean, String beanName)
            throws BeansException {
        return bean;
    }

    public Object postProcessAfterInitialization(Object bean, String beanName)
            throws BeansException {

        System.out.println("Bean '" + beanName + "' initialized");
        return bean;
    }
}
